package com.design_pattern._02_structure._04_proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Date;

public class V6_cglib {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Tank.class);
//        enhancer.setCallback(new LogCglibProxy());
        enhancer.setCallbacks(new MethodInterceptor[]{new LogCglibProxy()}); // 依旧是单代理，但是可以写多个回调，根据方法的不同选择回调
        enhancer.setCallbackFilter((method) ->{
            String methodName = method.getName();
            if ("getHelloInfo".equals(methodName)) {
                return 1;
            }
            return 0;
        });

        Tank tank = (Tank) enhancer.create();
        tank.move();
    }

    static class LogCglibProxy implements MethodInterceptor{
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("start in " + new Date().getTime());
//            Object invoke = method.invoke(o, objects);
            Object o1 = methodProxy.invokeSuper(o, objects);
//            methodProxy.invoke(o,objects); // 会发生循环调用
            System.out.println("stop in " + new Date().getTime());

            return o1;
        }
    }
}
